//
//  CAICameraOverlayView.m
//  CAIImagePickerControllerKit
//
//  Created by 海参 on 2022/8/2.
//

#import "CAICameraOverlayView.h"
#import <Masonry/Masonry.h>
#import "CAICameraOverlayBottomView.h"
#import "CAIImagePickerKitTool.h"
#import <MBProgressHUD/MBProgressHUD.h>

@interface CAICameraOverlayView ()<CAICameraOverlayBottomViewDelegate>

///顶部黑色背景
@property (nonatomic, strong) UIView *topContainerView;

@property (nonatomic, strong) UIButton *topCloseButton;

@property (nonatomic, strong) UIButton *previewBackButton;

@property (nonatomic, strong) CAIPhotoBrowser *photoBrowser;

@property (nonatomic, strong) CAICameraOverlayBottomView *bottomContainerView;

@end


@implementation CAICameraOverlayView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/


- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    if (self) {
        [self setUI];
        [self addMas];
    }
    return self;
}

- (void)setUI{
    [self addSubview:self.topContainerView];
    [self addSubview:self.bottomContainerView];
    [self addSubview:self.photoBrowser];
    [self addSubview:self.topCloseButton];
    [self addSubview:self.previewBackButton];
    

    self.limitCount = 9;
    [self didPickImagesBlock];
}

#pragma mark -

- (void)addMas
{
    CGFloat topContainerHeight = [CAIImagePickerKitTool safeAreaStatusBarHeight]-10>0?[CAIImagePickerKitTool safeAreaStatusBarHeight]-10:0;
    [self.topContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left);
        make.right.mas_equalTo(self.mas_right);
        make.top.mas_equalTo(self.mas_top);
        make.height.mas_equalTo(topContainerHeight);
    }];
    
    [self.topCloseButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(LCDScale_iPhone6(17-6));
        make.top.mas_equalTo(self.topContainerView.mas_bottom).offset(0);
        make.width.height.mas_equalTo(LCDScale_iPhone6(22+6*2));
    }];
    
    [self.previewBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left).offset(LCDScale_iPhone6(11));
        make.top.mas_equalTo(self.topContainerView.mas_bottom).offset(0);
        make.width.height.mas_equalTo(LCDScale_iPhone6(22+6*2));
    }];
    
    //    iPhone5 (320/568)      320/426.5
    //    iPhone SE2 (375/667):  375/500------
    //    iPhoneX  (375/812):    414/500
    //    iPhone 11（414/896）:   414/552
    [self.bottomContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left);
        make.right.mas_equalTo(self.mas_right);
        make.bottom.mas_equalTo(self.mas_bottom);
        make.height.mas_equalTo([CAICameraOverlayBottomView bottomViewHeight]);
    }];
    
    [self.photoBrowser mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.mas_left);
        make.right.mas_equalTo(self.mas_right);
        make.bottom.mas_equalTo(self.bottomContainerView.mas_top);
        make.top.mas_equalTo(self.topContainerView.mas_bottom);
    }];
}



#pragma mark -Action

- (void)cancelButtonAction:(id)sender{
    if ([self.delegate respondsToSelector:@selector(cameraOverlayViewDidCancel:)]) {
        [self.delegate cameraOverlayViewDidCancel:self];
    }
}

- (void)previewBackButtonAction:(id)sender{
    [self switchToCameraUI];
    [self.bottomContainerView backToCamera];
}

#pragma mark -方法

- (void)reloadUIWithTakePicture:(nullable CAICameraPhotoInfoModel *)photoModel{
    [self.bottomContainerView takePictureWithAddPhoto:photoModel];

    if (self.maxItemCount == 1) {
        [self switchToPhotoPreviewUI];
        self.photoBrowser.images = @[photoModel.photo];
    }
}


#pragma mark - CAICameraOverlayBottomViewDelegate

- (void)cameraOverlayBottomViewDidCancel:(CAICameraOverlayBottomView *)view{
    [self cancelButtonAction:nil];
}

- (void)cameraOverlayBottomViewDidTake:(CAICameraOverlayBottomView *)view{
    if ([self.delegate respondsToSelector:@selector(cameraOverlayViewDidTake:)]) {
        [self.delegate cameraOverlayViewDidTake:self];
    }
}
- (void)cameraOverlayBottomViewDidTakeLimitNumberNotAllow:(CAICameraOverlayBottomView *)view{
    
    NSString *toast = [NSString stringWithFormat:@"最多可以拍%@张哦",@(self.maxItemCount)];
    NSLog(@"%@",toast);
    if ([self.delegate respondsToSelector:@selector(cameraOverlayViewDidTakeLimitNumberNotAllow:)]) {
        [self.delegate cameraOverlayViewDidTakeLimitNumberNotAllow:self];
    }
    [self showToast:toast];
}

- (void)cameraOverlayBottomView:(CAICameraOverlayBottomView *)view didSelectItemAtIndex:(NSInteger)index{
    if (self.photoBrowser.hidden == YES) {
        self.photoBrowser.images = view.imageArray;
        [self switchToPhotoPreviewUI];
    }
    if (self.photoBrowser.currentImageIndex != index) {
        self.photoBrowser.currentImageIndex = index;
    }
}

- (void)cameraOverlayBottomViewDidSwitchPreviewToTakePhoto:(CAICameraOverlayBottomView *)view{
    [self switchToCameraUI];
}

- (void)cameraOverlayBottomView:(CAICameraOverlayBottomView *)view commitDeleteForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.photoBrowser.hidden) {
        self.photoBrowser.images = view.imageArray;
    }
}


- (void)didPickImagesBlock{
    ///确定选择
    __weak __typeof(&*self)weakSelf = self;
    self.bottomContainerView.didPickImagesBlock = ^(NSArray<UIImage *> * _Nonnull images, NSArray<CAIUIImagePickerCameraPhotoModel *> * _Nonnull models) {
        if ([weakSelf.delegate respondsToSelector:@selector(cameraOverlayView:didFinishPickingImages:imageModels:)]) {
            [weakSelf.delegate cameraOverlayView:weakSelf didFinishPickingImages:images imageModels:models];
        }
    };
}


- (void)switchToCameraUI{
    self.photoBrowser.hidden = YES;
    self.previewBackButton.hidden = YES;
    self.topCloseButton.hidden = !self.previewBackButton.hidden;
}

- (void)switchToPhotoPreviewUI{
    if (self.maxItemCount == 1) {
        [self switchToOnePhotoPreviewUI];
    }else{
        [self switchToMultiPhotoPreviewUI];
    }
}
- (void)switchToMultiPhotoPreviewUI{
    self.photoBrowser.hidden = NO;
    self.previewBackButton.hidden = NO;
    self.topCloseButton.hidden = !self.previewBackButton.hidden;
}

- (void)switchToOnePhotoPreviewUI{
    self.photoBrowser.hidden = NO;
    self.previewBackButton.hidden = NO;
    self.topCloseButton.hidden = !self.previewBackButton.hidden;
}

#pragma mark - CAIPhotoBrowserDelegate

- (void)photoBrowser:(CAIPhotoBrowser *)browser didSelectItemAtIndex:(NSInteger)index{
    
}

- (void)photoBrowser:(CAIPhotoBrowser *)browser willDisplayCellForItemAtIndex:(NSInteger)index{
    [self.bottomContainerView selectPreviewPhotosViewItemAtIndex:index];
}



#pragma mark -- toast

- (void)showToast:(NSString *)toast{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.color = [UIColor colorWithWhite:0 alpha:0.75f];
    hud.contentColor = [UIColor whiteColor];
    hud.label.text = toast;
    [hud hideAnimated:YES afterDelay:1.5];
}


#pragma mark -Setter


- (void)setMaxItemCount:(NSInteger)maxItemCount{
    if (_maxItemCount != maxItemCount) {
        _maxItemCount = maxItemCount>self.limitCount?self.limitCount:maxItemCount;
        self.bottomContainerView.maxItemCount = _maxItemCount;
    }
}


- (void)setCommonTintColor:(UIColor *)commonTintColor{
    if (_commonTintColor != commonTintColor) {
        _commonTintColor = commonTintColor;
        if (commonTintColor) {
            self.bottomContainerView.commonTintColor = commonTintColor;
        }
    }
}

#pragma mark -Getter


- (UIView *)topContainerView{
    if (!_topContainerView) {
        UIView *view = [[UIView alloc] init];
        view.backgroundColor = [UIColor blackColor];
        _topContainerView = view;
    }
    return _topContainerView;
}

- (UIButton *)topCloseButton
{
    if (!_topCloseButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[CAIImagePickerKitTool imageNamed:@"cancel_icon"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(cancelButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _topCloseButton = btn;
    }
    return _topCloseButton;
}

- (UIButton *)previewBackButton
{
    if (!_previewBackButton) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[CAIImagePickerKitTool imageNamed:@"back_icon"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(previewBackButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        btn.hidden = YES;
        _previewBackButton = btn;
    }
    return _previewBackButton;
}

- (CAICameraOverlayBottomView *)bottomContainerView{
    if (!_bottomContainerView) {
        CAICameraOverlayBottomView *view = [[CAICameraOverlayBottomView alloc] init];
        view.backgroundColor = [UIColor blackColor];
        view.delegate =self;
        _bottomContainerView = view;
    }
    return _bottomContainerView;
}


- (CAIPhotoBrowser *)photoBrowser{
    if (!_photoBrowser) {
        CAIPhotoBrowser *view = [[CAIPhotoBrowser alloc] init];
        view.hidden = YES;
        view.delegate = self;
        _photoBrowser = view;
    }
    return _photoBrowser;
}


- (NSArray *)photoArray{
    return self.bottomContainerView.imageArray;
}

@end
